#region Using

using System;
using System.Collections.Specialized;
using System.Data;
using System.Text;
using System.IO;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Serialization;
using System.Web;
using System.Web.Caching;
using BlogEngine.Core;
using BlogEngine.Core.Provider;
using BlogEngine.Core.Provider.Interfaces;

#endregion

namespace BlogEngine.Core.Provider.MSSQL
{
	/// <summary>
	/// Microsoft SQL Server Implementation of BlogProvider
	/// </summary>
	public class CIExtensionSettings : IExtensionSettings
	{
		/// <summary>
		/// Loads the settings from the provider.
		/// </summary>
		/// <returns></returns>
		public List<ManagedExtension> Load()
		{
			// check cache first
			List<ManagedExtension> settings = (List<ManagedExtension>) HttpContext.Current.Cache["Extensions"];
			
			if (settings != null)
				return settings;

			SQLManagedConnection myConn = SQLManagedConnection.GetConnection(Provider.DatabaseName);

			try
			{
				myConn.GetTextCommand("SELECT Settings FROM be_ExtensionSettings");

				object o = myConn.ExecuteScalar();

				if (o == null)
					return null;

				// convert to memory stream
				MemoryStream stream = new MemoryStream((byte[])o);

				using (TextReader reader = new StreamReader(stream))
				{
					XmlSerializer serializer = new XmlSerializer(typeof(List<ManagedExtension>));
					settings = (List<ManagedExtension>)serializer.Deserialize(reader);

					HttpContext.Current.Cache["Extensions"] = settings;

					return settings;
				}
			}
			finally
			{
				myConn.CloseIfNonTransactional();
			}
		}

		/// <summary>
		/// Saves the settings to the provider.
		/// </summary>
		/// <param name="settings"></param>
		public void Save(List<ManagedExtension> settings)
		{
			if (settings == null)
				throw new ArgumentNullException("settings");

			SQLManagedConnection myConn = SQLManagedConnection.GetConnection(Provider.DatabaseName);

			try
			{
				// serialize to memory stream
				MemoryStream stream = new MemoryStream();
				XmlSerializer serializer = new XmlSerializer(typeof(List<ManagedExtension>));
				XmlTextWriter writer = new XmlTextWriter(stream, System.Text.Encoding.UTF8);
				writer.Formatting = Formatting.Indented;
				writer.Indentation = 4;
				serializer.Serialize(writer, settings);
				stream = (MemoryStream)writer.BaseStream;

				// convert to bytes
				byte[] file = new byte[stream.Length];
				stream.Seek(0, SeekOrigin.Begin);
				stream.Read(file, 0, (int)stream.Length);

				myConn.GetTextCommand("DELETE FROM be_ExtensionSettings");
				myConn.ExecuteNonQuery();

				myConn.GetTextCommand("INSERT INTO be_ExtensionSettings (Settings) VALUES (@file)");

				myConn.AddInParameter("@file", DbType.Binary, file);
				myConn.ExecuteNonQuery();
			}
			finally
			{
				//if commit worked then this will do nothing
				myConn.Rollback();
			}
			
			HttpContext.Current.Cache["Extensions"] = settings;
		}
	}
}
